#include "stm32f10x.h"
#include "I2C.h"

/*引脚初始化*/
void I2C1_Init(void)
{
    
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
	RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1,ENABLE);
    
	GPIO_InitTypeDef GPIO_InitStructure;
 	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_OD;
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
    // PB8 -> SCL
    // PB9 -> SDA
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9;
 	GPIO_Init(GPIOB, &GPIO_InitStructure);
    
    /*
        I2C1 的默认引脚是在 PB6(SCL) 和 PB7(SDA)
        但是江协科技的 I2C 使用的是 PB8(SCL) 和 PB9(SDA)
        所以需要做引脚重映射
        记住，重映射之前需要开启AFIO的时钟

    */
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
    GPIO_PinRemapConfig(GPIO_Remap_I2C1,ENABLE);
    

	I2C_InitTypeDef I2C_InitStruct;
    I2C_StructInit(&I2C_InitStruct);
    

    I2C_InitStruct.I2C_Ack = I2C_Ack_Enable;
    /*
        必须同时设置 时钟速度 I2C_ClockSpeed 和 I2C_DutyCycle
        才能保证I2C运行处于一个较高频率的状态
    */
    I2C_InitStruct.I2C_ClockSpeed = 300000;
    I2C_InitStruct.I2C_DutyCycle = I2C_DutyCycle_2;
    I2C_Init(I2C1,&I2C_InitStruct);
	//OLED_W_SCL(1);
	//OLED_W_SDA(1);
  
    
    I2C_Cmd(I2C1,ENABLE);

}






static ErrorStatus wait_event(uint32_t I2C_EVENT){
    
    uint16_t count=0xffff;
    
    while(I2C_CheckEvent(I2C1,I2C_EVENT) == ERROR ){
        if(count--==0){
            return ERROR;
        }
    }
    return SUCCESS;
}



char * send_data( uint8_t Address,uint8_t * data,uint8_t length){


    I2C_GenerateSTART(I2C1,ENABLE);
    

    // 读取 状态寄存器
    // Start condition generated 的时候，继续往下执行
    //while(I2C_GetFlagStatus(I2C1,I2C_FLAG_SB)==RESET);
    
    if(wait_event(I2C_EVENT_MASTER_MODE_SELECT)==ERROR){
        
          
        I2C_GenerateSTOP(I2C1,ENABLE);
        
        return "i2c bus busy";
    }
    
    

    
    //从机地址
	I2C_Send7bitAddress(I2C1,Address,I2C_Direction_Transmitter);
    
    /* 读取 状态寄存器
        Address sent (Master)
     End of address transmission 的时候，继续往下执行
     For 7-bit addressing, the bit is set after the ACK of the byte
     Note: ADDR is not set after a NACK reception
    */
    //while(I2C_GetFlagStatus(I2C1,I2C_FLAG_ADDR)==RESET);
    if(wait_event(I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)==ERROR){
        I2C_GenerateSTOP(I2C1,ENABLE);
        return "slave addr not response";
    }
    
    /*
     等待数据寄存器为空（等待从机地址发送完成）
        EV8_1: TxE=1, shift register empty, data register empty, write Data1 in DR.

    */
    uint8_t count=0;
    //while(I2C_GetFlagStatus(I2C1,I2C_FLAG_TXE)==RESET && count<0xff){
        //count++;
    //}
    
    for (uint16_t i=0;i<length;i++){
    
        I2C_SendData(I2C1,data[i]);
        
        /* 等待数据寄存器为空（等待Data发送完成）
        When the acknowledge pulse is received, 
        the TxE bit is set by hardware and an interrupt is
        generated if the ITEVFEN and ITBUFEN bits are set.
        
        EV8: TxE=1, shift register not empty, data register empty, cleared by writing DR register .

        */
        //while(I2C_GetFlagStatus(I2C1,I2C_FLAG_TXE)==RESET);
        
        
        if(wait_event(I2C_EVENT_MASTER_BYTE_TRANSMITTING)==ERROR){
            I2C_GenerateSTOP(I2C1,ENABLE);
            return "failed to send data";
        }

        
    }


    /*
    EV8_2: TxE=1, BTF = 1, Program Stop request. 
    TxE and BTF are cleared by hardware by the Stop condition

    */
    wait_event(I2C_EVENT_MASTER_BYTE_TRANSMITTED);

    
	I2C_GenerateSTOP(I2C1,ENABLE);
    
    return (char *)0;
}


char * get_data(uint8_t Address,uint8_t register_addr,uint8_t * data,uint8_t data_count){

    I2C_GenerateSTART(I2C1,ENABLE);
    

    // 读取 状态寄存器
    // Start condition generated 的时候，继续往下执行
    //while(I2C_GetFlagStatus(I2C1,I2C_FLAG_SB)==RESET);
    
    if(wait_event(I2C_EVENT_MASTER_MODE_SELECT)==ERROR){
        I2C_GenerateSTOP(I2C1,ENABLE);
        return "i2c bus busy";
    }
    
    

    
    //从机地址
	I2C_Send7bitAddress(I2C1,Address,I2C_Direction_Transmitter);
    
    /* 读取 状态寄存器
        Address sent (Master)
     End of address transmission 的时候，继续往下执行
     For 7-bit addressing, the bit is set after the ACK of the byte
     Note: ADDR is not set after a NACK reception
    */
    //while(I2C_GetFlagStatus(I2C1,I2C_FLAG_ADDR)==RESET);
    if(wait_event(I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED)==ERROR){
        I2C_GenerateSTOP(I2C1,ENABLE);
        return "slave address not response";
    }
    
    // 写入要读取的寄存器地址
    I2C_SendData(I2C1,register_addr);
    wait_event(I2C_EVENT_MASTER_BYTE_TRANSMITTED);

    // 发送 i2c Restart 条件 
    I2C_GenerateSTART(I2C1,ENABLE);
    wait_event(I2C_EVENT_MASTER_MODE_SELECT);

    // 读取从机地址
    I2C_Send7bitAddress(I2C1,Address,I2C_Direction_Receiver);
    wait_event(I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED);
    
    for (uint8_t i=0;i<data_count;i++){
        
        wait_event(I2C_EVENT_MASTER_BYTE_RECEIVED);
    
        data[i] = I2C_ReceiveData(I2C1);
    }
    
    I2C_GenerateSTOP(I2C1,ENABLE);

    return (char *) 0;
}
